package com.zhihaoliang.coroutine.buss.channel.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/27 16:25
 * @des
 */
object ChannelProducer {

    @OptIn(ExperimentalCoroutinesApi::class)
    private fun CoroutineScope.produceSquares(): ReceiveChannel<Int> = produce {
        for (x in 1..5) {
            delay(300)
            send(x * x)
        }
    }

    fun onProducer(mainScope: CoroutineScope) = mainScope.launch {
        val squares = produceSquares()
        squares.consumeEach { log(it) }
        println("Done!")
    }
}